<template>
    <a-skeleton :animation="true" >
        <div class="left" ref="leftRef" v-if="chatList.length">
            <!-- 会话列表 -->
            <div v-for="item in filteredList(searchKeys)" :key="item.id" :class="['item', { 'item-style': chatIndex === item.topicId }]" @click="handleChat(item)">
                <div class="avatar">
                    <a-skeleton-shape shape="circle" style="width: 40px; height: 40px" v-if="loading || !chatList.length"/>
                    <template v-else>
                            <a-avatar v-if="item.avatar">
                                <img :src="item.avatar" alt="">
                            </a-avatar>
                            <a-avatar :style="{ backgroundColor: '#1055bc' }" v-else>
                                {{ item?.name?.slice(0, 1) }}
                            </a-avatar>
                            <span class="count flex" v-if="item?.unread > 0">{{ item.unread < 100 ? item.unread : 99 }}</span>
                    </template>
                </div>
                <div class="label">
                    <a-skeleton-line :rows="2" :line-height="15" v-if="loading"/>
                    <template v-else>
                        <div class="name">
                            <span>{{ item.name }}</span>
                            <span class="time">{{ formatChatTime(item?.sendTime || item?.lastMsg?.sendTime) }}</span>
                        </div>
                        <div class="content">
                            <!-- 31归档 32删除 33被移除群聊 -->
                            <template v-if="useUserStore().chatType.includes(item?.lastMsg?.type)">{{ item?.lastMsg?.content }}</template>
                            <template v-else>
                                <template v-if="item.chatType === 'app'">{{ item?.lastMsg?.content }}</template>
                                <template v-else>{{ item?.sendName ? `${item?.sendName}: ${item?.lastMsg?.content}` : '-' }}</template>
                            </template>
                        </div>
                    </template>
                </div>
            </div>
        </div>
        <a-empty v-if="!loading && !filteredList(searchKeys).length"></a-empty>
    </a-skeleton>
    <ComModal v-model:visible="modalVisible" title="新建多人会话" @handleCancel="modalVisible = false" @handleSubmit="myComponentRef?.handleSubmit()" :disabled="!myComponentRef?.formParams?.userIds?.length">
        <component :is="myComponent" ref="myComponentRef" @handleClose="handleClose" :userList="userList"></component>
    </ComModal>
</template>
<script lang="ts" setup>
import IconSystem from '@/assets/icon-system.png';
const AddGroup = defineAsyncComponent(() => import('./AddGroup.vue'));
import {useUserStore} from '@/store/modules/user';
import {loginId} from '@/utils/login';
import {formatChatTime} from '@/utils/index';
import * as ApiMsg from '@/api/msg';
import mitt from "@/utils/bus";
import {useCache} from "@/hooks/useCache";
const { wsCache } = useCache();
const userList = ref([]); // 用户列表
const chatList = ref([]); // 群聊列表
const chatIndex = ref(-1);
const modalVisible = ref(false);
const loading = ref(true);
const myComponent = ref(null);
const myComponentRef = ref(null);
const leftRef = ref(null);
const chatAddInfo = ref({}); // 新增群聊的信息
const searchKeys = ref('');
const currentInputVal = ref(''); // 当前发送消息输入框是否有值，有值则不能上下键操控
import { websocketStoreWithOut } from '@/store/modules/websocket';
let { setChatList, $state: { imStore } } = websocketStoreWithOut();

watch(() => imStore, e => {
    // console.log('获取imStore===111', e);
    try{
        userList.value = e?.userList || [];
        if(userList.value.length){
            mitt.emit('userList', userList.value);
        }
        nextTick(() => {
            chatList.value = e?.chatList || [];
        })
        let timer = setTimeout(() => {
            clearTimeout(timer);
            loading.value = false;
        }, 200);
    }finally{
        
    }
}, { deep: true, immediate: true })

watch(() => modalVisible.value, e => {
    if(!e){
        console.log('只烤====');
        myComponent.value = null;
        // let timer = setTimeout(() => {
        //     clearTimeout(timer);
        //     myComponentRef.value.comUploadRef.uploadUrl = '';
        //     myComponentRef.value?.formParamsRef.resetFields();
        // }, 100);
    }
})

// 使用watch监听isLoggedIn状态的变化

onMounted(() => {
    window.addEventListener('keydown', handleKeyDown);
})
onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown);
});

// 切换群聊
const handleChat = (row) => {
    console.log('切换===', {...row});
    // if(chatIndex.value === row.topicId) return;
    chatIndex.value = row.topicId;
    mitt.emit('handleChat', { ...row, isDetail: true });
    chatList.value.map(item => {
        return item.unread = item.topicId === chatIndex.value ? 0 : item.unread;
    })
}

// 计算过滤后的数据
const filteredList = computed(() => (keys) => {
    const query = keys?.trim().toLowerCase();
    if (query) {
        return chatList.value.filter(item => item.name.trim().toLowerCase().includes(query));
    } else {
        return chatList.value;
    }
});

// 新增
const handleAdd = () => {
    myComponent.value = AddGroup;
    modalVisible.value = true;
}

// 关闭modal
const handleClose = (value) => {
    modalVisible.value = false;
    chatAddInfo.value = {...value};
    console.log('添加===', value);
}

// 根据接收不同消息分类处理
mitt.on('sendMsg', value => {
    console.log('接收消息===左', {...value});
    const { sendId, sendName, sendTime, sendType = 'GROUP_MESSAGE', content, topicId, type } = value;
    // 本条消息是否是本人发送
    const isMySelf = loginId() === sendId;
    // SYSTEM_MESSAGE
    if(sendType === 'GROUP_MESSAGE'){
        let targetItem = chatList.value.find(item => item.topicId === topicId);
        const name = targetItem?.name || chatAddInfo.value?.name;
        if(targetItem){ // 这里处理已有的群
            targetItem = {
                ...targetItem,
                sendTime,
                messageType: sendType,
                lastMsg: { ...value }
            };
            targetItem.lastMsg.content = content.replace(/<p>/g, '').replace(/<\/p>/g, ' ').replace(/\s+/g,' ');
            if(targetItem.lastMsg.content.includes('<img')){
                targetItem.lastMsg.content = targetItem.lastMsg.content.replace(/<img.*?>/g, "[图片]");
            }
            targetItem.lastMsg.content = targetItem.lastMsg.content?.replace(/<[^>]*>/g,' ');
            // console.log('已有===', {...targetItem});
           if(type === 31){ // 归档
                console.log('群聊已被归档====');
                const tips = { btnType: 'return', btnTips: content, isDetail: true };
                targetItem.unread = targetItem.topicId === chatIndex.value ? 0 : (targetItem.unread || 0);
                const targetIndex = chatList.value.findIndex(item => item.topicId === topicId);
                chatList.value.splice(targetIndex, 1);
                chatList.value.unshift(targetItem);
                // 如果归档时，当前正处于当前群聊时, 重新获取详情
                if(chatIndex.value === topicId){
                    mitt.emit('handleChat', {...targetItem, ...tips});
                }
            }else if(type === 32){ // 删除
                const tips = { btnType: 'del', btnTips: content };
                // 是群主则直接删除当前群聊，否则展示删除相关信息
                const items = chatList.value.find(item => item.topicId === topicId);
                console.log('群聊已被删除====');
                const targetIndex = chatList.value.findIndex(item => item.topicId === topicId);
                chatList.value.splice(targetIndex, 1);
                mitt.emit('handleChat', {...targetItem, ...tips, isEmpty: true});
                setChatList(imStore.chatList);
            }else if(type === 33){ // 移除群聊
                console.log('移出群聊===');
                const tips = { btnType: 'remove', btnTips: content };
                const params = {
                    ...tips,
                    ...targetItem,
                    // unread: 0,
                }
                const targetIndex = chatList.value.findIndex(item => item.topicId === topicId);
                // 从数组中移除该项
                chatList.value.splice(targetIndex, 1);
                // 将该项插入到数组的第一个位置
                chatList.value.unshift(params);
                if(chatIndex.value === topicId){
                    mitt.emit('handleChat', {...targetItem, ...tips });
                }
            }else if(type === 21){ // 文字提示(移除、拉人、归档等等)
                const tips = { btnType: 'add', btnTips: content };
                targetItem.name = name;
                targetItem.sendName = sendName;
                // targetItem.unread = isMySelf ? targetItem.unread : targetItem.unread + 1;
                const targetIndex = chatList.value.findIndex(item => item.topicId === topicId);
                // console.log('文字提示===', isMySelf, {...targetItem});
                chatList.value.splice(targetIndex, 1);
                chatList.value.unshift(targetItem);
                if(chatIndex.value === topicId){
                    mitt.emit('handleChat', {...targetItem, ...tips });
                }
            }else{ // 文字消息
                // console.log('文字消息-====', targetItem.unread);
                targetItem.name = name;
                targetItem.sendName = sendName;
                // targetItem.unread = isMySelf ? 0 : (targetItem.unread || 0) + 1; // 发送消息当前人不做未读数+1，其他人+1
                const targetIndex = chatList.value.findIndex(item => item.topicId === topicId);
                chatList.value.splice(targetIndex, 1);
                chatList.value.unshift(targetItem);
            }
        }else{ // 这里处理新建的群，创建者第一次发消息，其他用户需要把此群添加进去，第二次发消息就不会走这里了
            if(type !== 32){
                ApiMsg.ApiChatListDetail(topicId).then((res) => {
                    const params = {
                        topicId,
                        name: res.name,
                        sendTime,
                        content: content?.replace(/<p>/g, '').replace(/<\/p>/g, ' ').replace(/\s+/g,' '),
                        isDetail: isMySelf,
                        chatType: 'chat',
                        btnType: 'add',
                        isFirst: true,
                        messageType: sendType,
                        unread: isMySelf ? 0 : 1,
                        lastMsg: {
                            ...value,
                        }
                    }
                    // console.log('未有===', {...params});
                    if(useUserStore().chatType.includes(type)){
                        chatList.value.unshift(params);
                        // 如果是群主则进入新建群的详情
                        if(isMySelf){
                            chatIndex.value = topicId;
                            mitt.emit('handleChat', params);
                        }
                    }
                }).catch((err) => {
                    console.log(err);
                });
            }
        }
    }else if(sendType === 'del'){
        chatList.value = chatList.value.filter(item => item.topicId !== value.topicId);
    }else if(sendType === 'read'){
        chatList.value.map(item => {
            return item.unread = item.topicId === topicId ? 0 : item.unread;
        })
    }else if(sendType === 'SYSTEM_MESSAGE'){ // 系统消息
        const items = chatList.value.find(item => item.messageType === sendType);
        console.log('系统消息===', chatList.value, items);
        const targetItem = {
            ...items,
            id: value.id,
            sendTime,
            name: '系统通知',
            chatType: 'app',
            avatar: IconSystem,
            messageType: sendType,
            unread: items ? ++items.unread : 1,
            lastMsg: { ...value, content: value.title }
        };
        if(!items){
            chatList.value.unshift(targetItem);
        }else{
            const targetIndex = chatList.value.findIndex(item => item.messageType === sendType);
            // console.log('targetIndex===', targetIndex, targetItem);
            chatList.value.splice(targetIndex, 1);
            chatList.value.unshift(targetItem); 
            if(chatIndex.value === items?.topicId){
                mitt.emit('handleChat', { ...targetItem, isCurrent: true });
            }
        }
        setChatList(imStore.chatList);
    }
    if(leftRef.value){
        leftRef.value.scrollTop = 0;
    }
})

// 上下键切换群聊
mitt.on('handlePreNext', ({ preNext, topicId }) => {
    // console.log('preNext, topicId===', preNext, topicId);
    let index = chatList.value.findIndex(item => item.topicId === topicId);
    if(preNext === 'pre'){ // 上
        index = index === 0 ? chatList.value.length - 1 : index - 1;
    }else if(preNext === 'next'){ // 下
        index = index === chatList.value.length - 1 ? 0 : index + 1;
    }
    handleChat(chatList.value[index]);
})

// 接收发送消息输入框的值
mitt.on('inputVal', value => {
    currentInputVal.value = value;
})

// 上下键切换群聊-处理不在输入框的情况(比如: 系统消息等)
const handleKeyDown = (event) => {
    // 当前处于系统消息时或者按上下键都可
    // console.log('键盘===', chatIndex.value >= 0, [38, 40].includes(event.keyCode), !currentInputVal.value);
    if(chatIndex.value >= 0 && [38, 40].includes(event.keyCode) && !currentInputVal.value){
        let index = chatList.value.findIndex(item => item.topicId === chatIndex.value);
        if(event.keyCode === 38){ // 上
            index = index === 0 ? chatList.value.length - 1 : index - 1;
        }else if(event.keyCode === 40){ // 下
            index = index === chatList.value.length - 1 ? 0 : index + 1;
        }
        handleChat(chatList.value[index]);
        currentInputVal.value = '';
    }
}

defineExpose({
    searchKeys,
    handleAdd
})
</script>
<style lang="scss" scoped>
.arco-skeleton{
    display: flex;
    flex-direction: column;
    background: #f9f9f9;
    .left{
        .item{
            display: flex;
            align-items: center;
            padding: 12px;
            position: relative;
            &:hover{
                cursor: pointer;
            }
            &-style{
                background: #e9e9e9;
                cursor: pointer;
            }
            .avatar{
                position: relative;
                .img{
                    width: 40px;
                    height: 40px;
                    border-radius: 50%;
                }
                .count{
                    position: absolute;
                    right: -6px;
                    top: -6px;
                    z-index: 2;
                    background: #f95557;
                    color: white;
                    width: 20px;
                    height: 20px;
                    border-radius: 50%;
                    justify-content: space-around;
                }
                &-default{
                    font-size: 20px;
                    font-weight: bold;
                    justify-content: space-around;
                    background-color: rgb(201, 180, 85);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-radius: 50%;
                    width: 40px;
                    height: 40px;
                    color: white;
                    font-size: 15px;
                    font-weight: normal;
                }
            }
            .msg{
                font-size: 30px;
                color: #ebe772;
                margin: 0 8px 0 12px;
            }
            
            .label{
                padding-left: 15px;
                color: #999;
                width: 100%;
                flex: 1;
                .name{
                    font-size: 15px;
                    font-weight: 500;
                    margin-bottom: 8px;
                    color: #333;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                }
                .content{
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 1;
                    /* autoprefixer: ignore next */
                    -webkit-box-orient: vertical;
                    /* autoprefixer: on */
                    word-wrap: break-word;
                }
                .time{
                    font-weight: normal;
                    font-size: 12px;
                    color: #999;
                }
            }
        }
    }
}
</style>